#!/bin/bash

if [ $(vncviewer --help 2>&1 | head -1 - | cut -d" " -f1) != "TightVNC" ];then
	echo "TighVNC viewer is not installed. Use 'sudo apt-get install xtightvncviewer' on Debian." >&2
	exit 1
fi

# Generate a random password
#  $1 = number of characters; defaults to 32
#  $2 = include special characters; 1 = yes, 0 = no; defaults to 1
function randpass() {
  [ "$2" == "0" ] && CHAR="[:alnum:]" || CHAR="[:graph:]"
    cat /dev/urandom | tr -cd "$CHAR" | head -c ${1:-32}
    echo
}

# Print usage info
function usage {
   echo ""
   echo "The script is ..."
	echo "\n"
}

# Default assignments
port=22
addr=localhost
force=0
disp=64
passwd=$(randpass 8)
newdisp=0
user=$USER
temp=$$

# Parsing command-line options 
TEMP=$(getopt -o fp:a:d:u:h --long force,port:,addr:,disp:,user:,help -- "$@")
if [ $? != 0 ] ; then exit 2 ; fi
eval set -- "$TEMP"
while true ; do
   case "$1" in
      -f|--force) 
			force=1			
			shift 
			;;
      -p|--port) 
			port=$2			
			shift 2 
			;;
		-u|--user) 
			user=$2			
			shift 2 
			;;
      -a|--addr)
			addr=$2			
			shift 2 
         ;;
		-d|--disp)
			disp=$2			
			shift 2
         ;;
		-h|--help)
			printf "$(usage)\n"
			exit 0
         ;;
      --) shift ; break ;;
      *) echo "Internal error!" ; exit 3 ;;
   esac
done

# Postprocessing of command-line options
sshcmd="/usr/bin/ssh -2 -p $port -c blowfish -l $user"
export VNC_VIA_CMD="$sshcmd -f -x -L %L:%H:%R %G sleep 20"

# Checking if TightVNCserver is running on the remote host 
echo $passwd | vncpasswd -f 2> /dev/null | $sshcmd $addr "mkdir -p ~/.vnc; touch ~/.vnc/passwd; cp ~/.vnc/passwd ~/.vnc/passwd.$temp 2> /dev/null; cat - > ~/.vnc/passwd; chmod 600 ~/.vnc/passwd"

# Trying to run VNC server on the remote side
$sshcmd $addr "tightvncserver -depth 16 -nevershared :$disp 2> /dev/null"
case $? in
	0) 
		echo "TightVNCserver has been successfully started on the remote host display :$disp"
		newdisp=1
		;;
	98)
		if [ $force -eq 0 ]; then
			echo "Given display number :$disp is in use on the remote side. Run the script with -f (or --force) to use it." 1>&2
			exit 4
		fi
		;;
	127)
		echo "TightVNCserver is not installed on the remote side. Fix and try again." 1>&2
		exit 5
		;;
	*)
		echo "Unrecognized response from the remote host while trying to start TightVNCserver." 1>&2
		exit 6
		;; 		
esac

# Run vncviewer
echo $passwd | vncviewer -autopass -via $addr :$disp
# Kill the display if one has been created
[ $newdisp -eq 1 ] && $sshcmd $addr "tightvncserver -kill :$disp 2> /dev/null"
# Remove password file
$sshcmd $addr "mv ~/.vnc/passwd.$temp ~/.vnc/passwd 2> /dev/null"



